// pages/shop/car/car.js
const call = require('../../utils/request.js')
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isOprate: false, //是否进入删除操作
    checkedIndex:[[]], //当前勾选
    checkedAll: false, //是否全选
    pageIndex:1, //当前页数
    sumPrice: '00.00', //总价
    total: 0, //购物车总数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let pages = getCurrentPages();
    let prePage = pages[pages.length - 2];
    prePage.getCarList();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 下拉到底，加载分页数据
   */
  loadPage(){
    if(this.data.list[this.data.pageIndex].length>0){
      this.setData({
        pageIndex: this.data.pageIndex+1
      })
      this.getList()
    }
  },

  /**
   * 获取购物车列表
   */
  getList(){
    wx.showLoading({
      title: '正在加载',
      mask:true
    })
    const page = this.data.pageIndex;
    call.post('/api/shop/cart_list',{
      page: page
    }).then(res=>{
      console.log("获取购物车列表",res.data.data)
      wx.hideLoading();
      if(page==1){
        this.setData({
          [`list`]: [[],res.data.data.list],
          total:res.data.data.meta.total,
        })}else{
        this.setData({
          [`list[${page}]`]: res.data.data.list
        })}
    })
  },

  /**
   * 购物车勾选
   */
  checked(e){
    const indexs = e.currentTarget.dataset.indexs;
    const index = e.currentTarget.dataset.index;
    const id1 = e.currentTarget.dataset.id1;
    const id2 = e.currentTarget.dataset.id2;
    let checkedIndex = this.data.checkedIndex;  //当前勾选的数组
    let nowChecked = this.data.list[indexs][index].checked || false; //当前是否勾选

    if(!checkedIndex[indexs]){
      // checkedIndex.splice(indexs,0,[])
      checkedIndex[indexs]=[];
    }
 
    if(checkedIndex[indexs].indexOf(index) == -1){
      checkedIndex[indexs].push(index)
    }else{
      checkedIndex[indexs].splice(checkedIndex[indexs].indexOf(index),1)
    }

    this.setData({
      [`list[${indexs}][${index}].checked`]: !nowChecked,
      checkedIndex:checkedIndex,
    })
    this.checkedAll(false);
    this.sumPrice();
  },
  
  /**
   * 购物车全选
   */
  checkedAll(checked){
    const list = this.data.list;
    const checkedIndex = this.data.checkedIndex;
    let isCheckedAll = true; //是否选中
    for(let i in list){
      if(!checkedIndex[i] || list[i].length != checkedIndex[i].length){
        isCheckedAll = false;
        break;
      }
    }

    //只判断是否勾取全选
    if(!checked){
      this.setData({
        checkedAll: isCheckedAll,
      })
      return;
    }

    //当前的相反全选操作
    let obj = {};
    let arr = [];
    if(isCheckedAll){
      for(let i in list){
        for(let y in list[i]){
          obj = Object.assign(obj,{
            [`list[${i}][${y}].checked`]: false
          })
        }
      }
    }else{
      for(let i in list){
        arr.push([])
        for(let y in list[i]){
          obj = Object.assign(obj,{
            [`list[${i}][${y}].checked`]: true
          })
          arr[i].push(parseInt(y))
        }
      }
    }
    obj = Object.assign(obj,{
      checkedIndex: arr,
      checkedAll: !isCheckedAll,
    })
    this.setData(obj);
    this.sumPrice();
  },

  /**
   * 数量操作
   */
  countOprate(e){
    const type = e.currentTarget.dataset.type;
    const indexs = e.currentTarget.dataset.indexs;
    const index = e.currentTarget.dataset.index;
    const price = e.currentTarget.dataset.price;
    const id1 = e.currentTarget.dataset.id1;
    const id2 = e.currentTarget.dataset.id2;
    let count = this.data.list[indexs][index].count;
    
    if(type == "add"){
      count++;
      wx.showLoading({
        title: '修改数量中',
        mask:true
      })
      call.post('/api/shop/add_to_cart',{
        product_id: id1,
        product_spec_id: id2,
        count: 1
      }).then(res=>{
        wx.hideLoading();
        if(res.data.code == 0){
          this.setData({
            [`list[${indexs}][${index}].count`]:count
          })
        }
      })
      //总计
      if(this.data.list[indexs][index].checked){
        this.sumPrice('add',price)
      }
    } else{
      count--;
      if(count>0){
        wx.showLoading({
          title: '修改数量中',
          mask:true
        })
        call.post('/api/shop/remove_from_cart',{
          product_spec_id: id2,
        }).then(res=>{
          wx.hideLoading();
          console.log(res.data.data)
          if(res.data.code == 0){
            if(count == 0){
              const list = this.data.list;
              list[indexs].splice(index,1);
              this.setData({
                list:list
              })
            }else{
              this.setData({
                [`list[${indexs}][${index}].count`]:count
              })
            } 
          }
        })
        //总计
        if(this.data.list[indexs][index].checked){
          this.sumPrice('del',price)
        }
      }
    }
  },

  /**
   * 总价格计算
   */
  sumPrice(type, price){
    let sumPrice = parseFloat(this.data.sumPrice).toFixed(2); //当前总价
    let list = this.data.list;
    if(type == 'add'){
      sumPrice = parseFloat(sumPrice) + parseFloat(price)
    } else if(type == 'del'){
      sumPrice = parseFloat(sumPrice) - parseFloat(price)
    }else{
      sumPrice = 0;
      for(let items of list){
        for(let i of items){
          if(i.checked){
            sumPrice += i.count * parseFloat(i.product_specific.price).toFixed(2)
          }
        }
      }
    }
    sumPrice = parseFloat(sumPrice).toFixed(2);
    this.setData({
      sumPrice
    })
  },

  /**
   * 删除 / 结算 操作
   */
  oprate(){
    if(this.data.isOprate){ //删除
      this.delGood();
    }else{  //结算
      this.submit();
    }
  },

  /**
   * 提交订单
   */
  submit(){
    let checkedIndex = this.data.checkedIndex;
    let arr = [];
    const list = this.data.list;

    for(let i in checkedIndex){
      for(let y of checkedIndex[i]){
        arr.push({
          cart_id:list[i][y].id,
          product_id:list[i][y].product_id,
          product_spec_id:list[i][y].product_spec_id,
          count:list[i][y].count,
          product_name:list[i][y].product.product_name,
          img_thum:list[i][y].product.img_thum,
          price:list[i][y].product_specific.price,
          specification:list[i][y].product_specific.specification,
          is_vip_product:list[i][y].is_vip_product,
          ship_fee_template:list[i][y].product.ship_fee_template
        })
      }
    }

    console.log(arr);
    if(arr.length == 0) {
      wx.showToast({
        title: '无选中商品',
        icon:'none'
      })
      return;
    }
    app.globalData.goodsList = arr;
    
    wx.navigateTo({
      url: '../confirm/confirm',
    })
  },

  /**
   * 批量删除
   */
  delGood(){
    let checkedIndex = this.data.checkedIndex;
    let arr = [];
    const list = this.data.list;

    for(let i in checkedIndex){
      for(let y of checkedIndex[i]){
        arr.push(list[i][y].id,)
      }
    }
    if(arr.length>0){
      wx.showModal({
        content:`确认要删除这${arr.length}种商品吗?`,
        success:res=>{
          if(res.confirm){
            call.post('/api/shop/muti_delete',{
              cart_ids: arr.join(","),
            }).then(res=>{
              wx.hideLoading();
              this.setData({
                pageIndex:1,
                checkedIndex:[],
              })
              this.getList();
            })
          }
        }
      })
    }else{
      wx.showToast({
        title: '请选择需要删除的商品',
        icon:'none'
      })
    }
    
  },

  /**
   * 切换删除/结算 操作
   */
  changeOprate(){
    this.setData({
      isOprate: !this.data.isOprate
    })
  },

  /**
   * 跳转到商城
   */
  toShop(){
    wx.switchTab({
      url: '../../pages/shop/index/index',
    })
  },
})